package net.csdra.libraryborrowing.service.book;

import net.csdra.libraryborrowing.domain.book.BookCopy;
import net.csdra.libraryborrowing.domain.book.BookCopyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by xiaomi on 2017/10/17.
 */
@Service
public class BookCopyServiceImpl implements BookCopyService {

    @Autowired
    BookCopyRepository bookCopyRepository;

    @Override
    public BookCopy getBookCopeById(GetBookCopyById getBookCopyById) {
        BookCopy bookCopy = bookCopyRepository.findOne(getBookCopyById.getBookCopeId());
        return bookCopy;
    }

    @Override
    public BookCopy getBookCopyByState(GetBookCopyByState getBookCopyByState) {
        List<BookCopy> bookCopyList = bookCopyRepository.findByMetaIdAndState(getBookCopyByState.getBookInfoId(), getBookCopyByState.getState());
        if (bookCopyList.size() > 0) {
            return bookCopyList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public Page<BookCopy> getBookCopyPageByBookInofoId(GetBookCopyPageByBookInofoId getBookCopyPageByBookInofoId) {
        Page<BookCopy> bookCopyPage = bookCopyRepository.findByMetaId(
                getBookCopyPageByBookInofoId.getBookInfoId(),
                new PageRequest(getBookCopyPageByBookInofoId.getPage(), getBookCopyPageByBookInofoId.getSize(), Sort.Direction.DESC, "lastModifiedTime")
        );
        return bookCopyPage;
    }
}
